<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <base href="${pageContext.request.contextPath}/"/>
    <title>我的名片 - 表格视图</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 复用现有CSS/JS资源，不新增依赖 -->
    <link href="static/bootstrap-3.3.5/css/bootstrap.css" rel="stylesheet">
    <style>
        .thead-blue {
            color: #fff;
            font-weight: bold;
            background-color: #337ab7;
        }
        .table-responsive {
            overflow-x: auto;
        }
        .batch-actions {
            margin-bottom: 10px;
        }
        .loading {
            color: #337ab7;
            font-size: 12px;
        }
        .required-mark {
            color: red;
            margin-right: 5px;
        }
    </style>
    <script src="static/jquery/jquery-1.10.2.min.js"></script>
    <script src="static/bootstrap-3.3.5/js/bootstrap.min.js"></script>
</head>
<body>

<!-- 消息提示（复用现有逻辑，接收后端传递的msg） -->
<c:if test="${not empty msg}">
    <div class="alert alert-info alert-dismissible fade in" role="alert">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
            ${msg}
    </div>
</c:if>

<div class="panel panel-primary">
    <div class="panel-heading">
        <h4 class="panel-title">我的名片</h4>
    </div>
    <div class="panel-body">
        <form action="mp/contact/listMyMpContact1" id="searchForm" method="post" class="form-horizontal" role="form">
            <div class="form-group">
                <div class="col-md-5">
                    <label for="name" class="col-md-4 control-label">姓名</label>
                    <div class="col-md-8">
                        <input type="text" id="name" name="name" class="form-control"
                               placeholder="请输入姓名" value="${name}">
                        <!-- 隐藏分页参数，用于搜索和分页跳转 -->
                        <input type="hidden" name="page" id="page" value="${pageInfo.current}">
                        <input type="hidden" name="pageSize" id="pageSize" value="${pageInfo.size}">
                    </div>
                </div>
                <div class="col-md-5">
                    <label for="sex" class="col-md-4 control-label">性别</label>
                    <div class="col-md-8">
                        <select name="sex" class="form-control" id="sex">
                            <option value="">--请选择--</option>
                            <option value="M" ${sex == 'M' ? 'selected' : ''}>男</option>
                            <option value="F" ${sex == 'F' ? 'selected' : ''}>女</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-5">
                    <label for="company" class="col-md-4 control-label">公司</label>
                    <div class="col-md-8">
                        <input type="text" id="company" name="company" class="form-control"
                               placeholder="请输入公司名" value="${company}">
                    </div>
                </div>
                <div class="col-md-5">
                    <label for="typeid" class="col-md-4 control-label">名片类型</label>
                    <div class="col-md-8">
                        <select name="typeid" class="form-control" id="typeid">
                            <option value="">--请选择--</option>
                            <c:forEach items="${cardtypes}" var="type">
                                <option value="${type.oid}" ${typeid == type.oid.toString() ? 'selected' : ''}>${type.type}</option>
                            </c:forEach>
                        </select>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-5">
                    <label for="mobile" class="col-md-4 control-label">电话</label>
                    <div class="col-md-8">
                        <input type="text" id="mobile" name="mobile" class="form-control"
                               placeholder="请输入电话" value="${mobile}">
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="col-md-8">
                        <button type="button" onclick="searchBtn()" class="btn btn-success">搜索名片</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 列表（核心修复：用VO的type字段替换双重循环，修正名片ID为cid） -->
<div class="panel panel-primary">
    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead>
            <tr class="thead-blue" align="center">
                <td>选择</td>
                <td>姓名</td>
                <td>名片类型</td>
                <td>性别</td>
                <td>公司</td>
                <td>电话</td>
                <td>操作</td>
            </tr>
            </thead>
            <tbody>
            <!-- 循环渲染名片数据（VO：UserContact） -->
            <c:forEach items="${pageInfo.records}" var="contact">
                <tr align="center">
                    <!-- 修复：名片ID用VO的cid（对应mp_contact.oid） -->
                    <td><input type="checkbox" name="oids" value="${contact.cid}"></td>
                    <td>${contact.name}</td>
                    <!-- 核心修复：直接取VO的type字段，删除双重循环匹配 -->
                    <td>${contact.type != null ? contact.type : '未分类'}</td>
                    <td>${contact.sex == 'M' ? '男' : '女'}</td>
                    <td>${contact.company}</td>
                    <td>${contact.mobile}</td>
                    <td>
                        <a href="mp/contact/mpContactInfo?oid=${contact.oid}" class="btn btn-info btn-xs">详情</a>
                        <a href="mp/contact/toUpdateMpContact?oid=${contact.oid}" class="btn btn-primary btn-xs">修改</a>
                        <button type="button" onclick="deleteContact(${contact.oid})" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#deleteModal">删除</button>
                    </td>
                </tr>
            </c:forEach>
            <c:if test="${pageInfo.total == 0}">
                <tr align="center">
                    <td colspan="7" class="text-warning">暂无名片数据</td>
                </tr>
            </c:if>
            <tr>
                <td align="center"><input type="checkbox" id="checkAll" onclick="checkAll(this)">全选</td>
                <td colspan="3">
                    <form class="form-inline" role="form">
                        <div class="form-group">
                            <label>移动到:</label>
                            <select name="typeid" id="batchTypeid" class="form-control">
                                <option value="">----请选择----</option>
                                <c:forEach items="${cardtypes}" var="type">
                                    <option value="${type.oid}">${type.type}</option>
                                </c:forEach>
                            </select>
                            <button type="button" id="moveBtn" onclick="moveContact()" class="btn btn-success">移动</button>
                        </div>
                    </form>
                </td>
                <!-- 批量发送 -->
                <td colspan="3">
                    <form class="form-inline" role="form">
                        <div class="form-group">
                            <label>发送给:</label>
                            <input type="hidden" id="empid" name="empid">
                            <div class="input-group">
                                <input type="text" id="empName" name="empName" readonly class="form-control" placeholder="请选择接收的员工">
                                <span class="input-group-btn">
                                    <button class="btn btn-info" type="button" data-toggle="modal" data-target="#selectempModal">请选择</button>
                                </span>
                            </div>
                            <button type="button" id="sendBtn" onclick="sendContact()" class="btn btn-success">发送</button>
                        </div>
                    </form>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>

<c:if test="${pageInfo.total > 0}">
    <div class="input-group col-md-6 col-md-offset-3">
        <div class="btn-group">
            <button onclick="gotoPage(1, ${pageInfo.size})" class="btn btn-primary" ${pageInfo.current == 1 ? 'disabled' : ''}>首页</button>
            <button onclick="gotoPage(${pageInfo.current - 1}, ${pageInfo.size})" class="btn btn-primary" ${pageInfo.current == 1 ? 'disabled' : ''}>上一页</button>
            <!-- 当前页码 -->
            <button class="btn btn-primary disabled">第${pageInfo.current}/${pageInfo.pages}页</button>
            <!-- 每页条数下拉框 -->
            <div class="btn-group">
                <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
                    每页${pageInfo.size}条 <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <li><a href="javascript:gotoPage(1,6)">6条/页</a></li>
                    <li><a href="javascript:gotoPage(1,12)">12条/页</a></li>
                    <li><a href="javascript:gotoPage(1,18)">18条/页</a></li>
                </ul>
            </div>
            <!-- 下一页：最后一页禁用 -->
            <button onclick="gotoPage(${pageInfo.current + 1}, ${pageInfo.size})" class="btn btn-primary" ${pageInfo.current == pageInfo.pages ? 'disabled' : ''}>下一页</button>
            <!-- 尾页：最后一页禁用 -->
            <button onclick="gotoPage(${pageInfo.pages}, ${pageInfo.size})" class="btn btn-primary" ${pageInfo.current == pageInfo.pages ? 'disabled' : ''}>尾页</button>
        </div>
    </div>
</c:if>

<!-- 1. 删除确认模态框（原有结构，无修改） -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">确认删除</h4>
            </div>
            <div class="modal-body">确定要删除该名片吗？</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDelete">确认</button>
            </div>
        </div>
    </div>
</div>

<!-- 2. 选择员工模态框（三级联动：部门→职位→员工） -->
<div class="modal fade" id="selectempModal" tabindex="-1" role="dialog" aria-labelledby="selectempModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="selectempModalLabel">选择员工</h4>
            </div>
            <div class="modal-body">
                <form action="" class="form-horizontal" role="form">
                    <div class="form-group">
                        <label for="dept" class="col-md-4 control-label">所属部门</label>
                        <div class="col-md-5">
                            <select name="dept" class="form-control" id="dept">
                                <option value="">--请选择--</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="job" class="col-md-4 control-label">所属职位</label>
                        <div class="col-md-5">
                            <select name="job" class="form-control" id="job">
                                <option value="">--请选择--</option>
                            </select>
                            <div id="jobLoading" class="loading" style="display: none;">加载中...</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="emp" class="col-md-4 control-label">员工信息</label>
                        <div class="col-md-5">
                            <select name="emp" class="form-control" id="emp" size="10">
                                <option value="" disabled>------请先选择部门和职位------</option>
                            </select>
                            <div id="empLoading" class="loading" style="display: none;">加载中...</div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="sub" class="btn btn-primary">确认选择</button>
            </div>
        </div>
    </div>
</div>

<!-- 3. 提示消息模态框（所有功能共用） -->
<div class="modal fade" id="alertModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-body" id="alertMsg"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 核心JS：修复变量未定义、按钮加载状态、参数传递错误 -->
<script type="text/javascript">
    // 全局变量：用于删除功能传递名片ID（VO的cid）
    var deleteOid;

    // 1. 删除功能：打开确认模态框
    function deleteContact(oid) {
        deleteOid = oid;
        $('#deleteModal').modal('show');
    }

    // 2. 单选全选功能（修复：仅选中数据行，排除批量操作行）
    function checkAll(obj) {
        // 获取所有数据行复选框（排除最后一行<tr>）
        var dataCheckboxes = document.querySelectorAll("tbody tr:not(:last-child) input[name='oids']");
        // 循环赋值选中状态
        for (var i = 0; i < dataCheckboxes.length; i++) {
            dataCheckboxes[i].checked = obj.checked;
        }
    }

    // 3. 页面加载完成后初始化（三级联动、事件绑定）
    $(document).ready(function () {
        // 3.1 单选联动全选框（新增：所有数据行选中则全选框勾选）
        $("tbody").on("change", "tr:not(:last-child) input[name='oids']", function() {
            var allDataCheckboxes = $("tbody tr:not(:last-child) input[name='oids']");
            var checkedCount = allDataCheckboxes.filter(":checked").length;
            // 全选框状态 = 数据行总数>0 且 选中数=总数
            $("#checkAll").prop("checked", allDataCheckboxes.length > 0 && checkedCount === allDataCheckboxes.length);
        });

        // 3.2 部门-职位-员工三级联动（修复加载逻辑，匹配现有后端接口）
        // 加载部门列表
        $.getJSON("hr/zz-department/listDeptUseSelect", function (listdept) {
            var deptSelect = $("#dept")[0];
            deptSelect.options.length = 1;
            if (listdept && listdept.length > 0) {
                for (var i = 0; i < listdept.length; i++) {
                    var dept = listdept[i];
                    deptSelect.options.add(new Option(dept.deptName, dept.oid));
                }
            } else {
                deptSelect.options.add(new Option("暂无部门数据", ""));
            }
        }).fail(function () {
            showAlert("部门数据加载失败，请刷新重试");
        });

        // 部门变更：加载对应职位
        $("#dept").change(function () {
            var deptId = $(this).val();
            resetSelect("job", "------请选择职位------");
            resetSelect("emp", "------请先选择职位------");
            if (!deptId) return;

            $("#jobLoading").show();
            $.getJSON("hr/zz-department-job/listDeptJobUseSelect", {deptid: deptId}, function (listjob) {
                $("#jobLoading").hide();
                var jobSelect = $("#job")[0];
                jobSelect.options.length = 1;
                if (listjob && listjob.length > 0) {
                    for (var i = 0; i < listjob.length; i++) {
                        var job = listjob[i];
                        jobSelect.options.add(new Option(job.jobName, job.jobid));
                    }
                } else {
                    jobSelect.options.add(new Option("该部门暂无职位", ""));
                }
                loadEmployees(); // 同步加载员工
            }).fail(function () {
                $("#jobLoading").hide();
                showAlert("职位数据加载失败");
            });
        });

        // 职位变更：加载对应员工
        $("#job").change(loadEmployees);
        function loadEmployees() {
            var deptId = $("#dept").val();
            var jobId = $("#job").val();
            resetSelect("emp", "------加载中...------");
            $("#empLoading").show();

            if (!deptId || !jobId) {
                $("#empLoading").hide();
                resetSelect("emp", "------请先选择部门和职位------");
                return;
            }

            $.getJSON("hr/emp/listEmpUseSelect", {deptid: deptId, jobid: jobId}, function (emps) {
                $("#empLoading").hide();
                var empSelect = $("#emp")[0];
                empSelect.options.length = 0;
                if (emps && emps.length > 0) {
                    for (var i = 0; i < emps.length; i++) {
                        var emp = emps[i];
                        empSelect.options.add(new Option(emp.empName, emp.oid));
                    }
                } else {
                    empSelect.options.add(new Option("该职位暂无员工", ""));
                }
            }).fail(function () {
                $("#empLoading").hide();
                showAlert("员工数据加载失败");
            });
        }

        // 重置选择框的通用方法
        function resetSelect(selectId, defaultText) {
            var select = $("#" + selectId)[0];
            select.options.length = 0;
            select.options.add(new Option(defaultText, ""));
        }

        // 3.3 确认选择员工：赋值给empid和empName
        $("#sub").click(function () {
            var empSelect = $("#emp")[0];
            var selectedOption = empSelect.options[empSelect.selectedIndex];
            if (!selectedOption || selectedOption.value === "") {
                showAlert("请选择有效员工");
                return;
            }
            // 赋值给隐藏字段和显示框
            $("#empid").val(selectedOption.value);
            $("#empName").val(selectedOption.text);
            $('#selectempModal').modal('hide');
        });

        // 3.4 打开员工选择模态框时重置
        $('#selectempModal').on('show.bs.modal', function () {
            resetSelect("dept", "--请选择--");
            resetSelect("job", "--请选择--");
            resetSelect("emp", "------请先选择部门和职位------");
            // 重新加载部门列表
            $.getJSON("hr/zz-department/listDeptUseSelect", function (listdept) {
                var deptSelect = $("#dept")[0];
                deptSelect.options.length = 1;
                if (listdept && listdept.length > 0) {
                    for (var i = 0; i < listdept.length; i++) {
                        var dept = listdept[i];
                        deptSelect.options.add(new Option(dept.deptName, dept.oid));
                    }
                } else {
                    deptSelect.options.add(new Option("暂无部门数据", ""));
                }
            });
        });

        // 3.5 执行删除操作（POST请求，匹配Controller，用VO的cid）
        $('#confirmDelete').click(function () {
            $.post("mp/contact/deleteMpContact", {oid: deleteOid}, function (success) {
                if (success) {
                    $("#alertMsg").text("删除成功");
                } else {
                    $("#alertMsg").text("删除失败");
                }
                $('#alertModal').modal('show');
                // 延迟刷新页面，让用户看到提示
                setTimeout(function () {
                    location.reload();
                }, 1500);
            });
            $('#deleteModal').modal('hide');
        });

        // 3.6 批量移动功能（修复：定义按钮变量、添加加载状态、用VO的cid）
        window.moveContact = function() {
            // 修复：获取移动按钮元素（原代码未定义moveBtn）
            var moveBtn = $("#moveBtn");
            var checkedBoxes = $("tbody tr:not(:last-child) input[name='oids']:checked");
            var typeid = $("#batchTypeid").val();
            var mids = "";

            // 拼接选中的名片ID（VO的cid）
            for (var i = 0; i < checkedBoxes.length; i++) {
                mids += checkedBoxes[i].value + ",";
            }
            mids = mids ? mids.slice(0, -1) : "";

            // 基础校验
            if (checkedBoxes.length === 0) {
                showAlert("请选择要移动的名片");
                return;
            }
            if (!typeid) {
                showAlert("请选择目标名片类型");
                return;
            }

            // 修复：添加按钮加载状态，防止重复点击
            moveBtn.prop("disabled", true).text("移动中...");
            // 发送POST请求
            $.post("mp/contact/moveContact", {mids: mids, typeid: typeid})
                .done(function(success) {
                    if (success) {
                        $("#alertMsg").text(`成功移动名片`);
                    } else {
                        $("#alertMsg").text("批量移动失败，请重试");
                    }
                })
                .fail(function() {
                    $("#alertMsg").text("服务器异常，移动失败");
                })
                .always(function() {
                    // 恢复按钮+刷新页面
                    setTimeout(function() {
                        moveBtn.prop("disabled", false).text("移动");
                        location.reload();
                    }, 1500);
                });
        }

        // 3.7 批量发送功能（修复：定义按钮变量、添加加载状态、优化提示文字）
        window.sendContact = function() {
            // 修复：获取发送按钮元素（原代码未定义sendBtn）
            var sendBtn = $("#sendBtn");
            var checkedBoxes = $("tbody tr:not(:last-child) input[name='oids']:checked");
            var empid = $("#empid").val();
            var empName = $("#empName").val();
            var mids = "";

            // 拼接选中的名片ID（VO的cid）
            for (var i = 0; i < checkedBoxes.length; i++) {
                mids += checkedBoxes[i].value + ",";
            }
            mids = mids ? mids.slice(0, -1) : "";

            //测试
            console.log("传递的名片ID：" + mids);
            if (mids === "") {
                showAlert("请选择要发送的名片");
                return;
            }
            //

            if (checkedBoxes.length === 0) {
                showAlert("请选择要发送的名片");
                return;
            }
            if (!empid) {
                showAlert("请选择接收员工");
                return;
            }

            // 修复：添加按钮加载状态，防止重复点击
            sendBtn.prop("disabled", true).text("发送中...");
            // 发送POST请求
            $.post("mp/contact/sendContact", {mids: mids, empid: empid})
                .done(function(success) {
                    if (success) {
                        $("#alertMsg").text(`成功发送名片`);
                    } else {
                        $("#alertMsg").text("批量发送失败，请重试");
                    }
                })
                .fail(function() {
                    $("#alertMsg").text("服务器异常，发送失败");
                })
                .always(function() {
                    // 恢复按钮+刷新页面
                    setTimeout(function() {
                        sendBtn.prop("disabled", false).text("发送");
                        location.reload();
                    }, 1500);
                });
        }
    });

    // 4. 分页跳转功能（原有逻辑，无修改）
    function gotoPage(page, pageSize) {
        document.getElementById("page").value = page;
        document.getElementById("pageSize").value = pageSize;
        document.getElementById("searchForm").submit();
    }

    // 5. 搜索提交功能（原有逻辑，无修改）
    function searchBtn() {
        document.getElementById("page").value = 1; // 搜索默认跳第一页
        document.getElementById("searchForm").submit();
    }

    // 6. 通用提示消息函数（所有功能共用）
    function showAlert(msg) {
        $("#alertMsg").text(msg);
        $('#alertModal').modal('show');
    }

    // 7. 全局AJAX错误处理（原有逻辑，无修改）
    $(document).ajaxError(function (event, xhr) {
        if (xhr.status === "403") {
            document.location.href = xhr.getResponseHeader("url");
        } else if (xhr.status !== "200") {
            showAlert("服务器错误，请重试");
        }
    });
</script>
</body>
</html>